import getLogger from '../utils/logger'
const LOG = getLogger('FilePicker')

import './FilePicker.less'

class FilePicker {

    constructor(element, options = {}) {
        this.element = element
        this.options = Object.assign({}, DEFAULT_OPTIONS, options || {})
        this.element.classList.add('FilePicker')
        validateOptions(this.options)
        createView.call(this)
    }
}

function validateOptions(options) {
    if (typeof options.onFileChange !== 'function')
        LOG.warn('onFileChange is not a function, please check your options.')
}

function createView() {
    let opt = this.options
    this.input = document.createElement('input')
    this.input.type = 'file'
    this.element.appendChild(this.input)

    this.span = document.createElement('span')
    this.span.textContent = opt.filepath || ''
    this.element.appendChild(this.span)

    this.button = document.createElement('button')
    this.button.innerText = opt.buttonText || '...'
    this.element.appendChild(this.button)

    this.span.addEventListener('click', () => handleClick.call(this))
    this.button.addEventListener('click', () => handleClick.call(this))
    this.input.addEventListener('change', () => handleFileChange.call(this))
}

function handleClick() {
    this.input.click()
}

function handleFileChange() {
    let filename = this.input.files.length > 0 ? this.input.files[0].name : null
    this.span.textContent = filename || ''
    if (!(this.options.onFileChange instanceof Function))
        return
    this.options.onFileChange.call(this, filename)
}

const DEFAULT_OPTIONS = {
    buttonText: '...',
    onFileChange: function(file) { }
}

export default FilePicker